﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;
using System.Data.OleDb;
using XWG.JWBST.JWBSTEntity;
using System.Data.OracleClient;
using XWG.JWBST.JWBSTBLL;
using XWG.Framework.AuthUtility;
using XWG.Framework;
using XWG.JWBST.JWBSTSPConst;
using XWG.Framework.AuthBLL;

namespace XWG.JWBST.JWBSTManagementApp.ZPXXCJ
{
    public partial class Datainteraction : System.Web.UI.Page
    {
        DataTable dtTbBstFraudFeedback = new DataTable();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

            }
        }

        protected void btn_Upload_Click(object sender, EventArgs e)
        {

            if (this.FileExecl.HasFile)
            {
                try
                {
                    string filetype = System.IO.Path.GetExtension(FileExecl.FileName);
                    if (filetype == ".xls" || filetype == ".xlsx")
                    {
                        string filepath = Server.MapPath("//ZPXXCJ/UploadExcel") + "\\" + FileExecl.FileName;
                        FileExecl.SaveAs(filepath);
                        DataTable dt = Excel.DataTableFromExcel(filepath, 0, 0);
                        if (dt != null)
                        {
                            int ImpNum = dt.Rows.Count;
                            if (ImpNum > 1)
                            {
                                int succNum = ExportMes(dt);
                                Logger(succNum, "1", filepath);
                                JsSet.Alert(this, "已完成数据导入,共导入诈骗信息" + succNum + "条数据");
                            }
                            else
                            {
                                //无内容
                                JsSet.Alert(this, "已选择的Excel文件中无导入数据");
                            }
                        }
                    }
                    else
                    {
                        //格式错误
                        JsSet.Alert(this, "请选择正确的Excel文件（.xls或.xlsx）");
                    }
                }
                catch (Exception ex)
                {
                    JsSet.Alert(this, "导入过程中出现错误,请联系管理员");
                }
            }
            else
            {
                //选择文件
                JsSet.Alert(this, "请选择要导入的Excel文件");
            }
        }

        ///// <summary>
        ///// 将Excel写入DataSet
        ///// </summary>
        ///// <param name="filepath"></param>
        ///// <returns></returns>
        //private static DataSet ImportExcel(string filepath)
        //{
        //    DataSet ds = new DataSet();
        //    FileInfo inf = new FileInfo(filepath);
        //    if (!inf.Exists)
        //    {
        //        return null;
        //    }
        //    string strConn = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath + ";Extended Properties='Excel 12.0;HDR=NO;IMEX=1'";
        //    OleDbConnection objConn = new OleDbConnection(strConn);
        //    try
        //    {
        //        objConn.Open();
        //        string strsql = "select * from [sheet1$]";
        //        OleDbDataAdapter oldadapter = new OleDbDataAdapter(strsql, strConn);
        //        oldadapter.Fill(ds);
        //        return ds;
        //    }
        //    catch (Exception ex)
        //    {
        //        throw;
        //    }
        //}

        private static int ExportMes(DataTable dt)
        {
            int SuccNum = 0;
            ResultModel mResultModel = new ResultModel();
            DataRow dr = null;
            for (int i = 1; i < dt.Rows.Count; i++)
            {
                dr = dt.Rows[i];

                TbBstFraudFeedback feback = new TbBstFraudFeedback();
                feback.Id = Guid.NewGuid().ToString();
                feback.Insideid = dr[0].ToString();
                feback.Tel = dr[1].ToString();
                feback.Fraudtypecontent = dr[2].ToString();
                feback.Operatorsname = dr[3].ToString();
                feback.Createdate = Convert.ToDateTime(dr[4].ToString());
                feback.Msgcontent = dr[5].ToString();
                feback.Result = dr[6].ToString();
                feback.Remark = dr[7].ToString();
                switch (feback.Operatorsname)
                {
                    case "中国移动":
                        feback.Operatorscode = "1";
                        break;
                    case "中国联通":
                        feback.Operatorscode = "2";
                        break;
                    case "中国电信":
                        feback.Operatorscode = "3";
                        break;
                    default:
                        feback.Operatorscode = "0";
                        break;
                }
                feback.Resultstatus = "2";
                feback.Movesign = "5";  //暂未确定

                TbBstFraudFeedbackBLL.DelInsertID(feback.Insideid);
                mResultModel = TbBstFraudFeedbackBLL.Insert(feback, "", false);
                if (mResultModel.ISSucceed)
                {
                    SuccNum += 1;
                }
            }
            return SuccNum;
        }

        //导出excel
        protected void btn_Export_Click(object sender, EventArgs e)
        {
            var mUser = AppOrganizatiOnUserBLL.Load(HttpContext.Current.Session["UserID"].ToString());
            if (mUser != null)
            {
                if (mUser.Bz5 == "1" || mUser.Bz5 == "2" || mUser.Bz5 == "3" || mUser.Bz5 == "4" || mUser.Bz5 == "管理员")
                {
                    int num = 0;
                    QueryByPage Q = new QueryByPage();
                    SqlConditionList sqllist = new SqlConditionList();
                    string reSta = this.selRESULTSTATUS.Value;
                    string startdt = this.texTimeStart.Value;
                    string enddt = this.texTimeEnd.Value;
                    string opCode = "";
                    switch (mUser.Bz5)
                    {
                        case "1":
                            opCode = "1";
                            break;
                        case "2":
                            opCode = "2";
                            break;
                        case "3":
                            opCode = "3";
                            break;
                        case "4":
                            opCode = "0";
                            break;
                        default:
                            break;
                    }
                    if (!string.IsNullOrEmpty(reSta))
                    {
                        sqllist.AddLogic(new SqlConditionList.SqlCondition(SqlCompareOper.EQUAL, TbBstFraudFeedbackConst.Columns.Resultstatus, reSta), SqlLogicOper.AND_LOGIC);
                    }
                    if (!string.IsNullOrEmpty(opCode))
                    {
                        sqllist.AddLogic(new SqlConditionList.SqlCondition(SqlCompareOper.EQUAL, TbBstFraudFeedbackConst.Columns.Operatorscode, opCode), SqlLogicOper.AND_LOGIC);
                    }
                    if (!string.IsNullOrEmpty(startdt))
                    {
                        sqllist.AddLogic(new SqlConditionList.SqlCondition(SqlCompareOper.NOT_LESS_THAN, TbBstFraudFeedbackConst.Columns.Receivedatetime, Convert.ToDateTime(startdt)), SqlLogicOper.AND_LOGIC);
                    }
                    if (!string.IsNullOrEmpty(enddt))
                    {
                        sqllist.AddLogic(new SqlConditionList.SqlCondition(SqlCompareOper.NOT_MORE_THAN, TbBstFraudFeedbackConst.Columns.Receivedatetime, Convert.ToDateTime(enddt)), SqlLogicOper.AND_LOGIC);
                    }

                    dtTbBstFraudFeedback = Q.GetRecordByPage("id 主键,tel 诈骗号码,fraudtypecontent 诈骗名义,operatorsname 运营商,createdate 举报时间,msgcontent 举报短信内容,result 处理反馈结果,remark 备注", sqllist.ToSql(), "CREATEDATE", 0, 1, TbBstFraudFeedbackConst.TableName, TbBstFraudFeedbackConst.FieldKey, "").Tables[0];
                    num = dtTbBstFraudFeedback.Rows.Count;
                    TbBstFraudFeedbackBLL.ModifiedState(sqllist.ToSql(),mUser.Bz5);  //修改状态
                    Excel.ExportFile("诈骗信息采集" + DateTime.Now.ToString("yyyMMdd") + ".xls", dtTbBstFraudFeedback);
                    Logger(num, "0", "");
                }
                else
                {
                    JsSet.Alert(this, "您没有相应的访问权限");
                }
            }
        }

        private static void Logger(int num, string type, string filepath)
        {
            var mUser = AppOrganizatiOnUserBLL.Load(HttpContext.Current.Session["UserID"].ToString());
            //type  0  下载  1上传
            TbBstFraudOperationhistory his = new TbBstFraudOperationhistory();
            his.Id = Guid.NewGuid().ToString();
            his.Operationtype = type;
            his.Username = mUser.UserLoginname;
            his.Operatorscode = mUser.Bz5;
      
            switch (his.Operatorscode)
            {
                case "1":
                    his.Operatorsname = "中国移动";
                    break;
                case "2":
                    his.Operatorsname = "中国联通";
                    break;
                case "3":
                    his.Operatorsname = "中国电信";
                    break;
                case "4":
                    his.Operatorsname = "其他";
                    break;
                default:
                    his.Operatorsname = "未知用户";
                    break;
            }
            his.Records = num;
            his.Filepath = filepath;
            his.Createdate = DateTime.Now;

            TbBstFraudOperationhistoryBLL.Insert(his, "", false);
        }
    }
}